package com.xhs.hawaii.framework;

import com.alibaba.druid.util.StringUtils;
import com.google.common.base.Throwables;
import com.xhs.hawaii.common.log.TraceLogIdUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import static com.xhs.hawaii.framework.GolbalResponseCodeEnum.EXCEPTION;
import static com.xhs.hawaii.framework.GolbalResponseCodeEnum.FAIL;

/**
 * http/https通用返回值
 */
@Data
public class GlobalResponse<T> {

    @ApiModelProperty(notes = "数据")
    private T data;
    @ApiModelProperty(notes = "不为空。等于200时表示业务成功，其他表示业务失败")
    private int statusCode = 200;
    @ApiModelProperty(notes = "错误信息，如果不为空，展示给用户")
    private String alertMsg;

    @ApiModelProperty(notes = "系统错误信息，供开发人员问题跟踪使用")
    private String errorMsg;
    @ApiModelProperty(notes = "日志跟踪号")
    protected String traceLogId;

    public GlobalResponse() {
    }

    public GlobalResponse(T data, String traceLogId) {
        this.traceLogId = traceLogId;
        this.data = data;
        this.alertMsg = "操作成功";
    }

    public static <T> GlobalResponse<T> success(T data) {
        return new GlobalResponse(data, TraceLogIdUtils.getTraceLogId());
    }

    public static <T> GlobalResponse<T> fail(String alertMsg) {
        GlobalResponse<T> resp = new GlobalResponse<T>();
        resp.setStatusCode(FAIL.getCode());
        resp.setTraceLogId(TraceLogIdUtils.getTraceLogId());
        resp.setAlertMsg(StringUtils.isEmpty(alertMsg) ? FAIL.getDesc() : alertMsg);
        resp.setErrorMsg(FAIL.getDesc());
        return resp;
    }

    public static <T> GlobalResponse<T> exception(Throwable e, String alertMsg) {
        GlobalResponse<T> resp = new GlobalResponse<T>();
        resp.setStatusCode(EXCEPTION.getCode());
        resp.setTraceLogId(TraceLogIdUtils.getTraceLogId());
        resp.setAlertMsg(StringUtils.isEmpty(alertMsg) ? EXCEPTION.getDesc() : alertMsg);
        resp.setErrorMsg(Throwables.getStackTraceAsString(Throwables.getRootCause(e)));
        return resp;
    }

    public static <T> GlobalResponse<T> httpError(Integer httpCode) {
        Integer code = null == httpCode ? EXCEPTION.getCode() : httpCode;
        GlobalResponse<T> resp = new GlobalResponse<T>();
        resp.setStatusCode(code);
        resp.setTraceLogId(TraceLogIdUtils.getTraceLogId());
        resp.setAlertMsg(EXCEPTION.getDesc());
        resp.setErrorMsg("http请求异常，Http statusCode = " + httpCode);
        return resp;
    }
}
